package com.zg.common.core.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Zxb
 */
@Slf4j
public class JsonUtil {
    public static final ObjectMapper OM = new ObjectMapper();

    static {
        // 接受不区分大小写的属性
        OM.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        // 反序列化忽略未知字段
        OM.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static ObjectNode on() {
        return OM.createObjectNode();
    }

    public static ArrayNode an() {
        return OM.createArrayNode();
    }

    /**
     * 将 JSON 字符串转换为指定类型的对象
     *
     * @param json  JSON 字符串
     * @param clazz 目标对象的 Class
     * @param <T>   泛型类型
     * @return 转换后的对象
     * @throws Exception 如果转换过程中出现错误
     */
    public static <T> T toObj(String json, Class<T> clazz) {
        try {
            return OM.readValue(json, clazz);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }

    }

    public static <T> T convertObj(Map map, Class<T> clazz) {
        try {
            return OM.convertValue(map, clazz);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static <T> List<T> convertList(List<Map> mapList, Class<T> clazz) {
        try {
            return mapList.stream()
                    .map(map -> convertObj(map, clazz))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static String toJson(Object map) {
        try {
            return OM.writeValueAsString(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
